package forgottenpassword;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;

@SuppressWarnings("serial")
public class RetrievePassword extends HttpServlet {
	
	private String email, msgBody;
	public HttpServletResponse respond;
		public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
			this.respond = resp;	
	        this.email = req.getParameter("email");     
	        if(this.email.equals(" "))
	        	notification(false);
	        else
	        	getUserDetails(); 		//getting user details for the database & calling the CreateMsgBody function
	        
        }
		
		//Getting the user account details for the google data store
		private void getUserDetails() throws IOException{
			DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
			Key accountKey = KeyFactory.createKey("Accounts", "accountName");
			
			Query query = new Query("Account", accountKey).addFilter("username", FilterOperator.EQUAL, this.email);
			Entity user = datastore.prepare(query).asSingleEntity();
			
			if(user.getProperty("username")== this.email)
				CreateMsgBody(user);  //Setting the message body
			else
				notification(false);
				

		}
		
		//Creating the message body
		//Calling the function to send the email.
		private void CreateMsgBody(Entity user) throws IOException{
			this.msgBody = "<html><body>" +
						"Dear "+ user.getProperty("firstName")+" " + user.getProperty("lastName") + 
								"</br></br> Your account details : </br>" +
						"Username : "+ user.getProperty("username")+ "</br>" +
								"Password : " + user.getProperty("password") + "</br>" +
										"Thank you. </br> Media Vault System Administrator.</body></html>";
			SendEmail();	//Sending the email.
		}
		
		//Sending account details to the user
		private void SendEmail() throws IOException{
			Properties props = new Properties();
	        Session session = Session.getDefaultInstance(props, null);
			
	        try {
	            Message msg = new MimeMessage(session);
	            msg.setFrom(new InternetAddress("jayan2005@gmail.com", "Administrator Media Vault"));
	            msg.addRecipient(Message.RecipientType.TO,
	                             new InternetAddress(this.email, "Mr. User"));
	            msg.setSubject("Media Vault - Forgotten Password");
	            msg.setText(this.msgBody);
	            Transport.send(msg);
	        } catch (AddressException e){
	        } catch (MessagingException e) {
			}
	        notification(true);
		}
		
		private void notification(boolean status) throws IOException{
			if(status = true){
				this.respond.getWriter().println("<p style=\"color:green; font-weight:bold;\">Password recovery is successful. Your User login deatils has been sent to your email. Please check your mails.</p>");
			}
			else{
				this.respond.getWriter().println("<p style=\"color:red; font-weight:bold;\">ERROR!!! - Can not find the entered email in the database. Please enter the correct email.</p>");
				/*
				this.respond.getWriter().println("<div id=\"\">" +
						"<div id=\"login_image\"><img src=\"images/warning.png width\"95\" height=\"95\"/></div>" + 
						"<div id=\"login_msg\">" +
							"<label style=\"font-weight:bold;\">ERROR!!!</label></br>" +
							"<label>This email address is not resgistered in Media vault database. Please check the email address again.</br><a href=\"/login.jsp\">Try again</a>" +
							"</label>" +
						"</div>" +
					"</div>");*/
			}
		}
	}
